<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>航次管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div id="takeoutMain">
      <a-form-model layout="inline" :model="form" :style="'margin-top:0px;'">
        <a-form-model-item label="船名">
          <a-select v-model="form.shipId" style="width:170px">
            <a-select-option value>全部</a-select-option>
            <a-select-option
              v-for="item in shipNameArray"
              :key="item.id"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="航次">
          <a-input v-model="form.voyageNumberLike" />
        </a-form-model-item>
        <a-form-model-item label="状态">
          <a-select v-model="form.status" :style="'width: 120px;'">
            <a-select-option value>全部</a-select-option>
            <a-select-option value="1">待执行</a-select-option>
            <a-select-option value="2">执行中</a-select-option>
            <a-select-option value="3">已结束</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-input-group compact>
            <a-select v-model="form.dateSearchType" @change="dateTypeChange" style="width:110px">
              <a-select-option :value="1">起航日期</a-select-option>
              <a-select-option :value="2">到达日期</a-select-option>
            </a-select>
            <a-range-picker :value="timeValue" @change="dateChange" style="width: 250px" />
          </a-input-group>
        </a-form-model-item>
        <a-form-model-item label="费用是否已录完">
          <a-select v-model="form.isCostRecorded" style="width:150px">
            <a-select-option value>全部</a-select-option>
            <a-select-option :value="1">是</a-select-option>
            <a-select-option :value="0">否</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="voyageCheck">查询</a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="voyagePlus">+ 创建航次</a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="exportExcel">导出Excel</a-button>
        </a-form-model-item>
      </a-form-model>
      <a-table
        :columns="columns"
        :loading="loading"
        :data-source="data"
        :style="'margin-top: 25px;'"
        :scroll="{x:1350}"
        :pagination="pagination"
        :row-key="(record,index) => index"
      >
        <span
          slot="status"
          slot-scope="text, record"
          :style="'display: flex; align-items: center;'"
        >
          <template v-if="record.status==1">
            <span class="yellow"></span>
            <span>待执行</span>
          </template>
          <template v-else-if="record.status==2">
            <span class="green"></span>
            <span>执行中</span>
          </template>
          <template v-else>
            <span class="grey"></span>
            <span>结束</span>
          </template>
        </span>
        <template slot="do" slot-scope="text, record">
          <a @click="detail(record)" style="margin-right:10px">详情</a>
          <a v-if="record.status==1" @click="del(record)" style="margin-right:10px">删除</a>
          <!-- <a v-if="record.status!=1" @click="showPicModal(record)">记载图</a> -->
          <a @click="showPicModal(record)">记载图</a>
        </template>
        <template slot="day" slot-scope="text, record">
          <span>{{record.sailingDays === 0 || !record.sailingDays ? '--' : record.sailingDays}}</span>
        </template>
      </a-table>
    </div>
    <!-- 创建航次 -->
    <a-modal v-model="createVoyage" title="创建航次" width="600px" destoryOnClose>
      <template slot="footer">
        <a-button key="back" @click="cancelCreate">取消</a-button>
        <a-button key="submit" type="primary" :loading="createStatus" @click="onCreate">确定</a-button>
      </template>
      <a-form-model
        ref="createFormRule"
        :rules="rules"
        :model="createForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :style="'margin-top:20px;padding-right:20px;'"
      >
        <a-form-model-item label="航次" prop="voyageNumber">
          <a-input v-model="createForm.voyageNumber" :max-length="10" />
        </a-form-model-item>
        <a-form-model-item label="船名" prop="shipId">
          <a-select v-model="createForm.shipId">
            <a-select-option
              v-for="item in shipNameArray"
              :key="item.id"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="计划起航日期" prop="plannedDepartureDate">
          <a-date-picker
            :locale="locale"
            @change="createRouteChange"
            :value="createValue"
            style="width: 100%"
          />
        </a-form-model-item>
        <a-form-model-item label="航线" prop="routeId">
          <div class="voyage tank_hangc">
            <a-button type="primary" @click="choseRoute">选择航线</a-button>
            <div class="scoll_ant-steps">
              <div :class="chosenRouteName.length > 2 ? 'scoll_ant-steps12' : ''">
                <a-steps progress-dot :current="chosenRouteName.length">
                  <a-step v-for="item in chosenRouteName" :key="item" :title="item" />
                </a-steps>
              </div>
            </div>
            <div v-if="chosenRouteName.length > 0" style="margin-top: 20px">
              <a-row :gutter="[16]">
                <a-col :span="12">航线类型：{{chosenRoute.type}}</a-col>
                <a-col :span="12">船舶类型：{{chosenRoute.isSelfOperation ? '自营' : '租赁'}}</a-col>
              </a-row>
              <a-row :gutter="[16]">
                <a-col :span="12">装载量：{{chosenRoute.loadingCapacity}}</a-col>
                <a-col :span="12">油耗（吨）：{{chosenRoute.oilConsumption}}</a-col>
              </a-row>
              <a-row :gutter="[16]">
                <a-col :span="12">航线租金支出（元）：{{chosenRoute.costPay}}</a-col>
                <a-col :span="12">航线租金收入（元）：{{chosenRoute.costIncome}}</a-col>
              </a-row>
            </div>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 选择航线 -->
    <a-modal
      v-model="choseRouteModal"
      title="选择航线"
      width="1200px"
      @cancel="cancelChose"
      destoryOnClose
    >
      <template slot="footer">
        <a-button key="back" @click="cancelChose">取消</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="onChose">确定</a-button>
      </template>
      <a-form-model :model="chosenForm" layout="inline" :style="'margin-top:20px;'">
        <a-form-model-item label="航线">
          <a-input v-model="chosenForm.nameLike" />
        </a-form-model-item>
        <a-form-model-item label="装载量">
          <a-input v-model="chosenForm.loadingCapacity" />
        </a-form-model-item>
        <a-form-model-item label="船舶类型">
          <a-select v-model="chosenForm.isSelfOperation" :style="'width: 120px;'">
            <a-select-option value>全部</a-select-option>
            <a-select-option value="1">自营</a-select-option>
            <a-select-option value="0">租赁</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="类型">
          <a-select v-model="chosenForm.type" :style="'width: 120px;'">
            <a-select-option value>全部</a-select-option>
            <a-select-option value="E">E</a-select-option>
            <a-select-option value="W">W</a-select-option>
            <a-select-option value="S">S</a-select-option>
            <a-select-option value="N">N</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="routeCheck">查询</a-button>
        </a-form-model-item>
      </a-form-model>
      <a-table
        :columns="routeColumns"
        :loading="loading"
        :data-source="routeData"
        :style="'margin-top: 50px;'"
        :row-selection="rowSelection"
        :pagination="pagination"
        :row-key="(record,index) => index"
      >
        <span slot="status" slot-scope="record" :style="'display: flex; align-items: center;'">
          <template v-if="record.status">
            <span class="green"></span>
            <span>正常</span>
          </template>
          <template v-else>
            <span class="red"></span>
            <span>冻结</span>
          </template>
        </span>
      </a-table>
    </a-modal>
    <!-- 查看记载图 -->
    <a-modal
      v-model="showPic"
      title="查看记载图"
      :footer="null"
      width="380px"
      centered
      @cancel="closePicModal"
      destoryOnClose
    >
      <viewer v-if="picArray.length > 0" :images="picArray" :options="{url: 'data-x'}">
        <template v-for="(src,index) in picArray">
          <img
            class="modalPicItem"
            :src="`${src}?x-oss-process=image/resize,h_100`"
            :data-x="src"
            :key="index"
            v-if="src"
          />
        </template>
      </viewer>
      <a-empty v-else />
    </a-modal>
  </div>
</template>
<script>
import 'viewerjs/dist/viewer.css'
import moment from 'moment'
import {
  queryShipNameList,
  queryShipVoyageList,
  delShipVoyageById,
  queryShipRouteList,
  addShipVoyage
} from '@/api/shipCenter'
import { commonExport } from '@/api/request'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
const fomrMessage = `必填项不能为空`
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '船名',
    dataIndex: 'shipName'
  },
  {
    title: '航次',
    dataIndex: 'voyageNumber'
  },
  {
    title: '船舶类型',
    dataIndex: 'isSelfOperation',
    _needName: true,
    customRender: (text, record, index) => {
      return record.isSelfOperation ? '自营' : '租赁'
    }
  },
  {
    title: '航线',
    dataIndex: 'routeName'
  },
  {
    title: '起航日期',
    dataIndex: 'departureDate'
  },
  {
    title: '到达日期',
    dataIndex: 'arriveDate',
    customRender: (text, record, index) => {
      return record.arriveDate || '--'
    }
  },
  {
    title: '航期（天）',
    dataIndex: 'sailingDays',
    scopedSlots: {
      customRender: 'day'
    }
  },
  {
    title: '状态',
    _needName: true,
    dataIndex: 'status',
    scopedSlots: {
      customRender: 'status'
    }
  },
  {
    title: '费用录入完成',
    dataIndex: 'isCostRecordedName'
    // _needName: true,
    // scopedSlots: {
    //   customRender: 'costRecorded'
    // }
  },
  {
    title: '操作',
    width: 200,
    key: 'do',
    scopedSlots: {
      customRender: 'do'
    }
  }
]
const routeColumns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '航线',
    dataIndex: 'name'
  },
  {
    title: '类型',
    dataIndex: 'type'
  },
  {
    title: '装载量',
    dataIndex: 'loadingCapacity',
    ellipsis: true
  },
  {
    title: '船舶类型',
    customRender: (text, record, index) => {
      return record.isSelfOperation ? '自营' : '租赁'
    }
  },
  {
    title: '油耗（吨）',
    dataIndex: 'oilConsumption',
    customRender: (text, record, index) => {
      return record.oilConsumption || '--'
    },
    ellipsis: true
  },
  {
    title: '航线租金支出（元）',
    width: 180,
    dataIndex: 'costPay',
    customRender: (text, record, index) => {
      return record.costPay || '--'
    },
    ellipsis: true
  },
  {
    title: '航线租金收入（元）',
    width: 180,
    dataIndex: 'costIncome',
    customRender: (text, record, index) => {
      return record.costIncome || '--'
    },
    ellipsis: true
  },
  {
    title: '状态',
    key: 'stauts',
    scopedSlots: {
      customRender: 'status'
    }
  }
]
export default {
  data () {
    return {
      locale,
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      shipNameArray: [], // 船名
      form: {
        isCostRecorded: '',
        shipId: '', // 船舶id
        voyageNumberLike: '', // 航次
        dateSearchType: 1, // 日期查询类型 1、起航日期 2、到达日期
        startDate: '', // 开始时间
        endDate: '', // 结束时间
        status: '' // 状态：1待执行，2执行中，3结束
      },
      createForm: {
        shipId: '',
        routeId: '',
        voyageNumber: '',
        plannedDepartureDate: undefined
      },
      createValue: '',
      chosenForm: {
        nameLike: '',
        loadingCapacity: '',
        isSelfOperation: '',
        type: ''
      },
      rules: {
        voyageNumber: [
          { required: true, message: fomrMessage, trigger: 'blur' }
        ],
        shipId: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        plannedDepartureDate: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        routeId: [{ required: true, message: fomrMessage, trigger: 'blur' }]
      },
      pageNum: 1,
      pageSize: 10,
      routePageNum: 1,
      loading: true,
      data: [],
      columns,
      pagination: {},
      createVoyage: false,
      choseRouteModal: false,
      routeColumns,
      routeData: [],
      selectedRowKeys: [],
      chosenRoute: {},
      chosenRouteName: [],
      btnControl: {},
      createStatus: false,
      timeValue: [],
      showPic: false,
      picArray: []
    }
  },
  computed: {
    rowSelection () {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        type: 'radio',
        selections: []
      }
    }
  },
  methods: {
    // 航次查询
    queryVoyage (paramData) {
      queryShipVoyageList(paramData)
        .then(res => {
          // // console.log(res)
          this.data = res.data.list
          let currentPage = this.pageNum
          this.$route.meta.s = paramData
          this.pagination = {
            current: currentPage,
            pageSize: res.data.pageSize,
            total: res.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            pageSizeOptions: ['10', '30', '50', '100', '500'],
            showTotal: total =>
              `共${total}条记录 第${currentPage}/${res.data.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.queryVoyage(paramData)
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.queryVoyage(paramData)
            }
          }
          this.loading = false
        })
        .catch(rs => {})
    },
    // 删除航次
    delVoyage (e) {
      delShipVoyageById({ id: e })
        .then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功！')
            setTimeout(() => {
              this.voyageCheck()
            }, 300)
          }
        })
        .catch(rs => {})
    },
    // 表单查询
    voyageCheck () {
      this.pageNum = 1
      let paramData = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        ...this.form
      }
      // // console.log(paramData)
      this.queryVoyage(paramData)
    },
    // 创建航次按钮
    voyagePlus () {
      if (!this.btnControl.create) {
        this.$message.error('您无此权限！')
        return false
      }
      this.createVoyage = true
    },
    // 表单创建航次
    formCreateVoyage (param) {
      let _this = this
      _this.createStatus = true
      addShipVoyage(param)
        .then(res => {
          // // console.log(res)
          if (res.code === 0) {
            _this.$message.success('航次创建成功！')
          }
          setTimeout(() => {
            _this.createStatus = false
            _this.pageNum = 1
            let paramData = {
              pageSize: _this.pageSize,
              pageNum: _this.pageNum,
              ..._this.form
            }
            // // console.log(paramData)
            this.queryVoyage(paramData)
            _this.cancelCreate()
          }, 200)
        })
        .catch(rs => {
          _this.createStatus = false
        })
    },
    // 详情
    detail (e) {
      // // console.log(e)
      this.$router.push(`voyageManagement/detail/${e.id}`)
    },
    // 删除
    del (e) {
      // // console.log(e)
      if (!this.btnControl.drop) {
        this.$message.error('您无此权限！')
        return false
      }
      let _this = this
      _this.$confirm({
        title: '删除航次后将不可不可恢复，确定删除？',
        centered: true,
        onOk () {
          _this.delVoyage(e.id)
        }
      })
    },
    // 导出
    exportExcel () {
      commonExport('/ship/exportShipVoyageList', {
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns
      })
    },
    // 日期控件
    dateChange (date, dateString) {
      // // console.log(date, dateString)
      this.timeValue = date
      this.form.startDate = dateString[0]
      this.form.endDate = dateString[1]
    },
    dateTypeChange () {
      this.timeValue = []
      this.form.startDate = ''
      this.form.endDate = ''
    },
    // 创建航次
    onCreate () {
      // // console.log(this.createForm)
      let _this = this
      _this.$refs.createFormRule.validate(valid => {
        if (valid) {
          _this.formCreateVoyage(_this.createForm)
        } else {
          // // console.log('error submit!!')
          return false
        }
      })
    },
    // 取消创建
    cancelCreate () {
      this.createVoyage = false
      this.createValue = ''
      this.chosenRouteName = []
      this.$refs['createFormRule'].resetFields()
    },
    // 选择航线
    choseRoute () {
      this.choseRouteModal = true
      this.routeModalReset()
      this.queryRoute({
        pageSize: this.pageSize,
        pageNum: this.routePageNum,
        status: '1'
      })
    },
    // 取消选择
    cancelChose () {
      this.choseRouteModal = false
      this.routeModalReset()
    },
    routeModalReset () {
      this.chosenForm = {
        nameLike: '',
        loadingCapacity: '',
        isSelfOperation: '',
        type: ''
      }
      this.selectedRowKeys = []
      this.chosenRoute = {}
    },
    // 确定选择
    onChose () {
      // // console.log(this.chosenRoute)
      if (!this.chosenRoute.id) {
        this.$message.error('请选择航线！')
        return false
      }
      // this.chosenRouteName = (this.chosenRoute.name).split('-')
      let chosenRouteName = this.chosenRoute.name.split('-')
      this.chosenRouteName = chosenRouteName
      this.createForm.routeId = this.chosenRoute.id
      this.choseRouteModal = false
      this.chosenForm = {
        nameLike: '',
        loadingCapacity: '',
        isSelfOperation: '',
        type: ''
      }
      this.selectedRowKeys = []
      // this.chosenForm = {
      //   nameLike: '',
      //   loadingCapacity: '',
      //   isSelfOperation: '',
      //   type: ''
      // }
    },
    // 查询航线
    routeCheck () {
      this.pageNum = 1
      let paramData = {
        pageSize: this.pageSize,
        pageNum: this.routePageNum,
        status: '1',
        ...this.chosenForm
      }
      // // console.log(paramData)
      this.queryRoute(paramData)
    },
    // 航线数据
    queryRoute (paramData) {
      queryShipRouteList(paramData)
        .then(res => {
          // // console.log(res)
          this.routeData = res.data.list
          let currentPage = this.routePageNum
          this.pagination = {
            current: currentPage,
            pageSize: res.data.pageSize,
            total: res.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            showTotal: total =>
              `共${total}条记录 第${currentPage}/${res.data.pages}页`,
            onChange: pageNum => {
              this.routePageNum = pageNum
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.routePageNum,
                ...this.form
              }
              this.queryRoute(paramData)
            },
            onShowSizeChange: (current, size) => {
              this.routePageNum = current
              this.pageSize = size
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.routePageNum,
                ...this.form
              }
              this.queryRoute(paramData)
            }
          }
          this.loading = false
        })
        .catch(rs => {})
    },
    onSelectChange (record, selected, selectedRows, nativeEvent) {
      this.selectedRowKeys = record
      this.chosenRoute = selected[0]
    },
    createRouteChange (date, dateString) {
      this.createValue = date
      this.createForm.plannedDepartureDate = dateString
    },
    showPicModal (e) {
      let voyagePics = e.voyagePics ? e.voyagePics.split(',') : []
      this.picArray = voyagePics
      this.showPic = true
      // // console.log(voyagePics)
    },
    closePicModal () {
      this.showPic = false
    }
  },
  created () {
    this.$nextTick(() => {
      this.btnControl = this.$root._bc
    })
    queryShipNameList({status: 1})
      .then(res => {
        // // console.log(res)
        this.shipNameArray = res.data
      })
      .catch(rs => {})
    let originObj = this.$route.meta.s
    this.listAssign(this.form, originObj)
    if (originObj) {
      this.pageSize = originObj.pageSize
      this.pageNum = originObj.pageNum
      this.form.startDate = originObj.startDate
      this.form.endDate = originObj.endDate
      if (originObj.startDate) {
        this.timeValue = [moment(originObj.startDate), moment(originObj.endDate)]
      } else {
        this.timeValue = []
      }
    }
    this.queryVoyage({
      ...this.form,
      pageSize: this.pageSize,
      pageNum: this.pageNum
    })
  },
  beforeRouteEnter (to, from, next) {
    if (from.name !== 'voyageManagementDetail' || to.query.f !== '1') {
      to.meta.s = null
    }
    next()
  }
}
</script>
<style lang="less" scoped>
.green {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #00a854;
  margin-right: 5px;
}
.red {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #f04134;
  margin-right: 5px;
}
#takeoutMain {
  padding: 24px;
  margin: 24px;
  background: #fff;
  min-height: 700px;
  .yellow {
    background: #ffdf25;
    display: inline-block;
    width: 5px;
    height: 5px;
    border-radius: 50%;
    margin-right: 5px;
  }
  .grey {
    background: #7f7f7f;
    display: inline-block;
    width: 5px;
    height: 5px;
    border-radius: 50%;
    margin-right: 5px;
  }
}
.voyage {
  border: 1px solid #d7d7d7;
  border-radius: 4px;
  min-height: 260px;
  padding: 10px 20px;
}
.modalPicItem {
  width: 100px;
  height: 100px;
  margin: 5px;
  border: 1px solid #eee;
  border-radius: 5px;
}
</style>
<style lang="less" scoped>
//创建航次选择航线弹窗
.scoll_ant-steps {
  width: 395px;
  height: 35px;
  margin-top: 15px;
}
.scoll_ant-steps12 {
  overflow-x: scroll;
  overflow-y: hidden;
  padding: 5px 0;
}
.scoll_ant-steps12::-webkit-scrollbar-track {
  border-radius: 5px;
  background-color: #f2f2f2;
}
.scoll_ant-steps12::-webkit-scrollbar {
  height: 4px; /*设置滚动条样式*/
  background-color: #fff;
}
.scoll_ant-steps12::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: #c1c1c1;
}

.tank_hangc .scoll_ant-steps .ant-steps-dot .ant-steps-item-content {
  width: 75px;
}
.tank_hangc .scoll_ant-steps .ant-steps-item-title {
  font-size: 12px;
  width: 75px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.tank_hangc .scoll_ant-steps .ant-steps-dot .ant-steps-item-icon {
  margin-left: 35px;
}
.tank_hangc .scoll_ant-steps .ant-steps-dot .ant-steps-item-tail {
  margin: 0 0 0 160px;
}
.tank_hangc .scoll_ant-steps12 .ant-steps-dot .ant-steps-item-tail::after,
.ant-steps-dot.ant-steps-small .ant-steps-item-tail::after {
  margin-left: -56px;
}
</style>
